﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

namespace EnterpriseLibraryExtensions.Events.Aggregation
{
    /// <summary>
    /// The TypeFilteringScopeOptions class makes it possible to aggregate events by their type. 
    /// This will discard any but the original event of a specific type that was raised within a scope.
    /// </summary>
    public class TypeFilteringScopeOptions : IScopeOptions
    {
        /// <summary>
        /// Filters the provided enlistedEventHandlers and returns a filtered read-only collection.
        /// </summary>
        /// <param name="enlistedEventHandlers">The enlistedEventHandlers that needs to be filtered.</param>
        /// <returns>A ReadOnlyCollection of enlisted event handlers. List is guaranteed to never be null.</returns>
        /// <exception cref="System.ArgumentNullException">Thrown if enlistedEventHandlers parameter is null.</exception>
        public ReadOnlyCollection<IEnlistedEventHandler> RemoveDuplicates(IEnumerable<IEnlistedEventHandler> enlistedEventHandlers)
        {
            if (enlistedEventHandlers == null)
            {
                throw new ArgumentNullException("enlistedEventHandlers");
            }

            var filteredEventHandlers = new List<IEnlistedEventHandler>();

            foreach (var enlistedEventHandler in enlistedEventHandlers)
            {
                IEnlistedEventHandler handler = enlistedEventHandler;
                if (!filteredEventHandlers.Any(feh => feh.EventHandler.EventType == handler.EventHandler.EventType))
                {
                    filteredEventHandlers.Add(enlistedEventHandler);
                }
                else
                {
                    EventAggregationTracer.TraceInformation("Removed duplicate event handler {0}", enlistedEventHandler);
                }
            }

            return new ReadOnlyCollection<IEnlistedEventHandler>(filteredEventHandlers);
        }
    }
}
